package com.example.filter;

import com.alibaba.fastjson.JSON;
import com.example.config.ShiroSessionManager;
import com.example.util.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;


@Component
public class SessionCheckFilter extends UserFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        String token = WebUtils.toHttp(request).getHeader(ShiroSessionManager.AUTHORIZATION);
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setCharacterEncoding("UTF-8");

        String responseJson;
        if (StringUtils.isEmpty(token)) {
            responseJson = JSON.toJSONString(Response.createFailResp("请登录")); //这里需要引入fastjson

        } else {
            responseJson = JSON.toJSONString(Response.createFailResp("token失效"));
        }

        httpResponse.getWriter().print(responseJson);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        return false;
    }
}
